package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 * @version 1.0
 * @description: 课程信息变更监听器
 * @date 2024/3/15 17:49
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {
    private final ILearningLessonService learningLessonService;

    /**
     * 监听下单购买课程的消息 -> 新增课程到用户课表（Day2 - 课程）
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY

    ))
    public void listenLessonPay(OrderBasicDTO order){
        //1、消息健壮性的处理
        if(ObjectUtil.isEmpty(order) || ObjectUtil.isEmpty(order.getCourseIds()) || ObjectUtil.isEmpty(order.getUserId())){
            log.error("接受订单支付MQ消息，内容有误");
            return;
        }

        //2、添加课程
        log.debug("监听到用户{}的订单{}，需要添加课程{}到用户课表",order.getUserId(),order.getOrderId(),order.getCourseIds());
        learningLessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }




    //退款后，立刻移除课表中的课程
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY

    ))
    public void listenLessonRefund(OrderBasicDTO order){
        //1、消息健壮性的处理
        if(ObjectUtil.isEmpty(order) || ObjectUtil.isEmpty(order.getCourseIds()) || ObjectUtil.isEmpty(order.getUserId())){
        return;
        }
        log.debug("监听到用户{}的订单{}，需要移除课程{}到用户课表",order.getUserId(),order.getOrderId(),order.getCourseIds());
        //2、移除课程
        learningLessonService.deleteCartByUserAndCourseIds(order.getUserId(),order.getCourseIds());
    }
}
